package com.alibaba.aliper.agent;

import java.net.InetAddress;

import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;
import org.kohsuke.args4j.Option;

import com.alibaba.aliper.agent.sys.CpuMonitor;
import com.alibaba.aliper.agent.sys.CpuPercentage;
import com.alibaba.aliper.server.interfaces.AliperRemoteControll;
import com.caucho.hessian.client.HessianProxyFactory;

/**
 * Hello world!
 *
 */
public class CpuClient 
{
    public static void main( String[] args ) throws Exception
    {
    	CpuClient client = new CpuClient();
    	CmdLineParser cmdLineParser = new CmdLineParser(client);
		try {
			cmdLineParser.parseArgument(args);
		} catch (CmdLineException e) {
			System.err.println(e.getMessage());
			System.out.println("Usage:");
			cmdLineParser.printUsage(System.out);
			return;
		}
    	
     client.run();

    }
    
    @Option(name = "-s", usage = "serverURL,the hessian service address.", metaVar="serverURL",required = true)
	private String serverUrl = null;
    
    @Option(name = "-p", usage = "project", metaVar="project",required = false)
	private String project = "project";
    
    @Option(name = "-c", usage = "chart", metaVar="chart",required = false)
	private String chart = "chart";
    
    @Option(name = "-a", usage = "agent", metaVar="agent",required = false)
	private String agent = null;
    
    @Option(name = "-i", usage = "interval. Sampling interval in milliseconds ", required = false)
	private int interval = 500;

	private void run() throws Exception {
	    HessianProxyFactory factory = new HessianProxyFactory();
	    AliperRemoteControll remote = (AliperRemoteControll) factory.create(AliperRemoteControll.class, serverUrl);
	    CpuMonitor monitor = new CpuMonitor();
	     if(agent == null){
	    	 agent = InetAddress.getLocalHost().getHostAddress();
	     }
	    while(true){
	    	CpuPercentage per = monitor.getCpuPercentage();
	    	double user = per.getUser(0);
	    	double sys = user + per.getSystem(0);
	    	remote.report(project,agent, chart, "user", monitor.getEndState().getTime(), (int)(user*100));
	    	remote.report(project,agent, chart, "system", monitor.getEndState().getTime(), (int)(sys*100));
	    	//remote.report("arandaServer", "linux Server2", "cpu/sys", monitor.getEndState().getTime(), per.getSystem(0));
	    	Thread.sleep(interval);
	    }
	}
}
